const express = require(`express`)
const router = express.Router()
const mongoose = require('mongoose');
const trans  = require('./myglobal').trans;
const ShujiVoter = mongoose.model('ShujiVoter');
const Teacher = mongoose.model('Teacher');
// ShujiVoter.find({number:'10347'}).exec((err,doc)=>{
//     var j=2;
// });
// var names = [
//     "刘晓华",
// ,"邓高强",
// ,"张燕",
// ,"钟远强",
// ,"赵淑敏",
// ,"廖海生",
// ,"吴国庆",
// ,"张玮",
// ,"潘利红",
// ,"潘琦华",
// ,"余爱民",
// ,"吴志毅",
// ,"魏春忠",
// ,"赵云辉",
// ,"梁筱红",
// ,"郭立银"];
// Teacher.updateMany({name:{$in:names}},{$push:{role:'参评党支书'}}).exec((e,doc)=>{

//     console.log(e);
// })
// ShujiVoter.insertMany(votes,function(err,docs){
//     var j=2
// });
// ShujiVoter.find({}).exec((err,votes)=>{
//     votes.forEach(async vote=>{
//         var teacher = await Teacher.findOne({name:vote.name});
//         ShujiVoter.updateOne({name:teacher.name},{$set:{number:teacher.number}}).exec((err,doc)=>{
//             console.log("success");
//         })
//     })
   
// })
router.get('/shujiVoter',async (req,res,next)=>{
    //
    try{
       
        var shujiVoters = ShujiVoter.find(JSON.parse(req.query.query));
        console.log("sessionID "+req.sessionID);
        if( trans[req.sessionID])
        shujiVoters.session( trans[req.sessionID])
       if(req.query.populate)
       {
            req.query.populate.forEach(p=>{
            shujiVoters.populate(JSON.parse(p))
        })
    }
        if(req.query.skip)
        shujiVoters.skip(JSON.parse(req.query.skip))
       if(req.query.limit)
        shujiVoters.skip(JSON.parse(req.query.limit))
        if(req.query.sort)
        shujiVoters.sort(JSON.parse(req.query.sort));
        var result = await shujiVoters.exec();
        res.jsonp(result);
    }catch(e){
        res.status(500).send(e);
    }
    //
});
router.delete('/ShujiVoter',async (req,res,next)=>{
    try{
    var removeQuery =  ShujiVoter.deleteMany(req.body.query);
    if( trans[req.sessionID])
    removeQuery.session( trans[req.sessionID])
    var result = await removeQuery.exec();
    res.jsonp(result);
    }catch(e){
        res.status(500).send(e);
    }
})
router.post('/ShujiVoter',async (req,res,next)=>{
    try{
        var results = null;
        if( trans[req.sessionID])
         results = await ShujiVoter.create(req.body, { session:  trans[req.sessionID] });
        else
        results = await ShujiVoter.create(req.body);
         res.jsonp(results);
    }catch(e){
        res.status(500).send(e);
    }
})
router.put('/ShujiVoter',async (req,res,next)=>{
    try{
    var updateQuery =  ShujiVoter.updateMany(req.body.query,req.body.update);
    if( trans[req.sessionID])
    updateQuery.session( trans[req.sessionID])
    var result =  await updateQuery.exec();
    res.jsonp(result);
    }catch(e){
        res.status(500).send(e);
    }
})
module.exports = router